package com.hmall.item.listener;

import com.hmall.common.constant.ESConstants;
import com.hmall.common.constant.MQConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
@RequiredArgsConstructor
@Slf4j
public class DeleteItemDocListener {

    private final RestHighLevelClient client;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.ITEM_DELETE_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(name = MQConstants.ITEM_EXCHANGE_DIRECT_NAME),
            key = MQConstants.ITEM_DELETE_ROUTING_KEY
    ))
    public void deleteItemDoc(Long id) {
        try {
            DeleteRequest request = new DeleteRequest(ESConstants.INDEX_NAME, String.valueOf(id));
            client.delete(request, RequestOptions.DEFAULT);
            log.info("删除索引成功，id:{}", id);
        } catch (Exception e) {
            log.error("删除索引失败，id:{}, 异常信息：{}", id, e.getMessage());
        }
    }
}
